package net.kaaass.poplan.ingress.api;

import net.kaaass.poplan.util.LocationUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Entities {
    public static JSONObject fetchEntitie(String tile) throws Exception {
        String[] tiles = {tile};
        return fetchEntitie(new JSONArray(tiles));
    }

    public static JSONObject fetchEntitie(JSONArray tiles) throws Exception {
        return Ingress.requestAPI(IngressAPIs.API_ENTITIES, (new JSONObject().put("tileKeys", tiles))).getJSONObject("result").getJSONObject("map");
    }

    public static JSONObject fetchEntitie(String[] tiles) throws Exception {
        return fetchEntitie(new JSONArray(tiles));
    }

    public static List<JSONArray> fetchEntities(double lng1, double lat1, double lng2, double lat2, int zoom) {
        String[] bounds = LocationUtil.geneTileKeys(lng1, lat1, lng2, lat2, 0, 8, zoom);
        List<JSONArray> r = new ArrayList<>();
        JSONArray tile = new JSONArray();
        JSONObject obj;
        try {
            for (int i = 0; i < bounds.length / 4; i++) { // 典型的垃圾代码
                int rest = bounds.length - i * 4;
                for (int ii = 0; ii < ((rest > 4) ? 4 : rest); ii++)
                    tile.put(ii, bounds[ii]);
                obj = fetchEntitie(tile);
                for (int ii = 0; ii < ((rest > 4) ? 4 : rest); ii++)
                    r.add(obj.getJSONArray(bounds[ii]));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return r;
        }
    }

    public static JSONArray getPortals(List<JSONArray> arrs) {
        JSONArray r = new JSONArray();
        JSONArray el;
        for (JSONArray arr : arrs) {
            for (int i = 0; i < arr.length(); i++) {
                el = arr.getJSONArray(i);
                if (!el.getJSONArray(2).getString(0).equals("p"))
                    continue;
                r.put(el);
                System.out.printf("Portal read-in: %s or %s", el.getJSONArray(2).getString(8), el.getJSONArray(2).getString(1));
            }
        }
        return r;
    }
}
